package Service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import DAO.CompanyDAO;
import DAO.MarketDAO;
import Entity.Company;
import Entity.Market;
import Helpers.CompanyHelper;
import Helpers.MarketHelper;
import VOs.CompanyVO;
import VOs.MarketVO;

public class CompanyService {
	
	public void create(CompanyVO companyVo, EntityManager em) {
		Company company = new Company();
		CompanyDAO.create(company, em);
	}

	public List<CompanyVO> readCompanies(MarketVO marketVo, EntityManager em) {
		Market market = new MarketHelper().toEntity(marketVo);
		market = MarketDAO.find(market, em);
		List<Company> companies = market.getCompanies();
		ArrayList<CompanyVO> companiesVo = new ArrayList<CompanyVO>(companies.size());
		for (Company company : companies) {
			companiesVo.add(company.tovo());
		}
		return companiesVo;
	}

	public void update(CompanyVO companyVo, CompanyVO newOne, EntityManager em) {
		Company company = new CompanyHelper().toEntity(companyVo);
		company = CompanyDAO.read(company, em);
		Company newCompany = new CompanyHelper().toEntity(newOne);

		Market oldMarket = company.getMarket();
		oldMarket.getCompanies().remove(company);
		oldMarket.getCompanies().add(newCompany);

		company.setDescription(newCompany.getDescription());
		company.setMarket(newCompany.getMarket());
		company.setName(newCompany.getName());
		company.setStokes(newCompany.getStokes());
		company.setSymbol(newCompany.getSymbol());

		CompanyDAO.update(company, em);
		MarketDAO.update(oldMarket, em);
	}

	public void delete(CompanyVO companyVo, EntityManager em) {
		Company company = new CompanyHelper().toEntity(companyVo);
		company = CompanyDAO.read(company, em);
		CompanyDAO.delete(company, em);
	}

}
